package com.credithc.eagleeye.api.job;
import com.credithc.eagleeye.api.factory.ESFactory;
import com.credithc.eagleeye.api.service.SettingService;
import com.credithc.eagleeye.api.service.StatService;
import com.credithc.eagleeye.api.vo.PlatformVo;
import com.credithc.eagleeye.api.vo.StatConditionVo;
import com.credithc.eagleeye.api.vo.StatHourVo;
import com.credithc.eagleeye.api.vo.StatVo;
import com.credithc.eagleeye.util.FastJsonConvert;
import com.credithc.framework.es.util.ElasticSearchUtil;
import com.credithc.framework.utils.date.DateTools;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.credithc.eagleeye.util.MixUtil.ISO_DATETIME_TIME_ZONE_FORMAT_WITH_MILLIS;
/**
 * 描 述: <br/>
 * 作 者: zhangjin<br/>
 * 创 建：2019年02月18日<br/>
 * 版 本：v1.0.0<br>
 * <p>
 * 历 史: (版本) 作者 时间 注释 <br/>
 */
@Component
@Slf4j
public class StatHourJob {
    public static final String EAGLE_HOUR_STAT_INDEX = ".eagleeye-hour-stat";
    public static final String EAGLE_HOUR_STAT_TYPE = "stat";
    @Autowired
    private SettingService settingService;
    @Autowired
    private StatService statService;

    @Scheduled(cron = "0 30 0/1 * * ?")
    public void statHour(){
        List<PlatformVo> platformVos = settingService.loadAllPlatform();
        ElasticSearchUtil elasticSearchUtil = ESFactory.getInstance();
        for(PlatformVo platformVo : platformVos) {

            StatConditionVo statConditionVo = new StatConditionVo();
            //获取上一小时时间
            Date previousHour = DateTools.getDateByNewHour(new Date(), -1);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH");
            statConditionVo.setPlatformName(platformVo.getName());
            statConditionVo.setFromDate(formatter.format(previousHour)+" :00:00");
            statConditionVo.setToDate(formatter.format(previousHour)+" :59:59");
            List<StatVo> statErrorVos = statService.statError(statConditionVo);
            if (log.isDebugEnabled()) {
                log.debug("platformName:{},statErrorVos:{}", platformVo.getName(), FastJsonConvert.convertObjectToJSON(statErrorVos));
            }

            //按照每小时计算百分位
            List<StatVo> statPercentHourVos = statService.statPercent(statConditionVo, DateHistogramInterval.HOUR);
            if (log.isDebugEnabled()) {
                log.debug("platformName:{},statPercentVos:{}", platformVo.getName(), FastJsonConvert.convertObjectToJSON(statPercentHourVos));
            }

            StatHourVo statHourVo = new StatHourVo();
            statHourVo.setStatDate(ISO_DATETIME_TIME_ZONE_FORMAT_WITH_MILLIS.format(DateTools.Date19ToDate(statConditionVo.getFromDate())));
            statHourVo.setPlatformName(platformVo.getName());
            statHourVo.setTotalCount(0L);
            statHourVo.setOkCount(0L);
            statHourVo.setErrorCount(0L);
            statHourVo.setPercent99(0L);
            statHourVo.setPercent995(0L);

            if (statErrorVos != null && !statErrorVos.isEmpty()) {
                Map<String, StatVo> subStatMap = statErrorVos.get(0).getSubStatMap();
                StatVo statOK = subStatMap.get("OK");
                StatVo errorOK = subStatMap.get("ERROR");

                if(statOK!=null) {
                    statHourVo.setOkCount(statOK.getCount());
                }
                if(errorOK!=null) {
                    statHourVo.setErrorCount(errorOK.getCount());
                }
                statHourVo.setTotalCount(statHourVo.getOkCount()+statHourVo.getErrorCount());
            }

            if(statPercentHourVos!=null && !statPercentHourVos.isEmpty()){
                Map<String, StatVo> subStatMap = statPercentHourVos.get(0).getSubStatMap();
                StatVo stat99Vo = subStatMap.get("99");
                StatVo stat995Vo = subStatMap.get("99.5");

                if(stat99Vo!=null) {
                    statHourVo.setPercent99(stat99Vo.getCount());
                }
                if(stat995Vo!=null) {
                    statHourVo.setPercent995(stat995Vo.getCount());
                }
            }

            log.info("statHourVo:{}", FastJsonConvert.convertObjectToJSON(statHourVo));
            String id = platformVo.getName() + "-" + DateTools.StringDateTo14(statConditionVo.getFromDate());
            elasticSearchUtil.insertOrUpdateDocument(EAGLE_HOUR_STAT_INDEX, EAGLE_HOUR_STAT_TYPE, id,statHourVo);
        }
    }
}
